from sys import argv,exit
from json import load, dump
from datetime import datetime, timedelta
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QListWidget, QListWidgetItem, QLabel, QPushButton, QDialog,
                             QLineEdit, QTextEdit, QComboBox, QMessageBox, QMenu, QProgressBar,
                             QInputDialog, QAction, QFrame, QSizePolicy, QShortcut, QGridLayout,
                             QScrollArea, QGraphicsDropShadowEffect, QFileDialog,QDialogButtonBox)
from PyQt5.QtCore import Qt,pyqtSignal
from PyQt5.QtGui import (QFont, QColor, QPalette, QKeySequence, QCursor)

SAVE_FILE = "card_data.json"

class Card:
    def __init__(self, title, answer, tags, proficiency=0, last_practiced=None):  # 修改参数为tags
        self.title = title
        self.answer = answer
        self.tags = tags if isinstance(tags, list) else [tags]  # 确保是列表
        self.proficiency = proficiency
        self.last_practiced = last_practiced or datetime.now()

    def update_proficiency(self, delta):
        self.proficiency = max(0, min(100, self.proficiency + delta))
        self.last_practiced = datetime.now()
        
    def decay_proficiency(self):
        if self.proficiency >= 100:
            return
        time_since = datetime.now() - self.last_practiced
        if time_since > timedelta(hours=6):
            decay = (time_since // timedelta(hours=6)) * 20
            self.proficiency = max(0, self.proficiency - decay)
            self.last_practiced = datetime.now()

    def to_dict(self):
        return {
            'title': self.title,
            'answer': self.answer,
            'tags': self.tags,  # 修改为tags
            'proficiency': self.proficiency,
            'last_practiced': self.last_practiced.isoformat()
        }
    
    @classmethod
    def from_dict(cls, data):
        # 兼容旧数据：若存在'tag'字段则转换为列表
        tags = data.get('tags', [data.get('tag')] if 'tag' in data else [])
        return cls(
            data['title'],
            data['answer'],
            tags,
            data['proficiency'],
            datetime.fromisoformat(data['last_practiced'])
        )

class CardWidget(QWidget):
    rightClicked = pyqtSignal() 
    doubleClicked = pyqtSignal() 
    MAX_WIDTH = 400
    MIN_WIDTH = 280
    ASPECT_RATIO = 0.6
    
    def __init__(self, card, parent=None):
        super().__init__(parent)
        self.card = card
        self.initUI()
        self.setupShadow()
        
    def initUI(self):
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.setMinimumSize(self.MIN_WIDTH, int(self.MIN_WIDTH * self.ASPECT_RATIO))
        self.setMaximumSize(self.MAX_WIDTH, int(self.MAX_WIDTH * self.ASPECT_RATIO))
        
        layout = QVBoxLayout()
        layout.setContentsMargins(15, 15, 15, 15)
        
        title = QLabel(self.card.title)
        title.setFont(QFont("Segoe UI", 14, QFont.Bold))
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("color: #2c3e50; margin-bottom: 12px;")
        title.setWordWrap(True)
        
        progress = QProgressBar()
        progress.setValue(self.card.proficiency)
        progress.setTextVisible(False)
        progress.setFixedHeight(10)
        progress.setStyleSheet("""
            QProgressBar {
                background: rgba(0,0,0,0.1);
                border-radius: 5px;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #3498db, stop:1 #2980b9);
                border-radius: 5px;
            }
        """)
        
        layout.addWidget(title)
        layout.addWidget(progress)
        self.setLayout(layout)
        
        self.setStyleSheet("""
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                stop:0 #ffffff, stop:1 #f8f9fa);
            border-radius: 12px;
            border: 1px solid rgba(0,0,0,0.05);
        """)
        
    def setupShadow(self):
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(15)
        shadow.setColor(QColor(0, 0, 0, 30))
        shadow.setOffset(3, 3)
        self.setGraphicsEffect(shadow)
        
    def mousePressEvent(self, event):
        if event.button() == Qt.RightButton:
            self.rightClicked.emit() 
            
    def mouseDoubleClickEvent(self, event):
        self.doubleClicked.emit() 

class PreviewDialog(QDialog):
    def __init__(self, card, parent=None):
        super().__init__(parent)
        self.setWindowTitle("卡片预览")
        self.setFixedSize(600, 400)
        self.initUI(card)
        
    def initUI(self, card):
        layout = QVBoxLayout()
        layout.setContentsMargins(25, 25, 25, 25)
        
        title = QLabel(card.title)
        title.setFont(QFont("Segoe UI", 18, QFont.Bold))
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("color: #2c3e50; margin-bottom: 20px;")
        
        answer = QTextEdit(card.answer)
        answer.setReadOnly(True)
        answer.setFont(QFont("Segoe UI", 14))
        answer.setStyleSheet("""
            QTextEdit {
                background: #f8f9fa;
                border-radius: 8px;
                padding: 15px;
                border: 1px solid #eee;
            }
        """)
        
        layout.addWidget(title)
        layout.addWidget(answer)
        self.setLayout(layout)

class NewCardDialog(QDialog):
    def __init__(self, tags, card=None, parent=None):
        super().__init__(parent)
        self.card = card
        self.tags = tags.copy()  # 使用副本
        self.setWindowTitle("编辑卡片" if card else "新建卡片")
        self.setFixedSize(500, 400)
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)
        
        self.title_input = QLineEdit()
        self.title_input.setPlaceholderText("输入标题...")
        
        self.answer_input = QTextEdit()
        self.answer_input.setPlaceholderText("输入答案...")
        
        # self.tag_combo = QComboBox()
        # self.tag_combo.addItems(tags)
        
        input_style = """
            font: 14px Segoe UI;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
        """
        self.title_input.setStyleSheet(input_style)
        self.answer_input.setStyleSheet(input_style + "min-height: 100px;")
        # self.tag_combo.setStyleSheet(input_style)
        
        # 初始化标签列表（包含卡片原有标签）
        self.tags_list = QListWidget()
        self.tags_list.setSelectionMode(QListWidget.MultiSelection)
        for tag in self.tags:
            self.tags_list.addItem(QListWidgetItem(tag))
        
        # 如果编辑卡片，添加缺失标签并选中
        if self.card:
            for tag in self.card.tags:
                if tag not in self.tags:
                    self.tags.append(tag)
                    self.tags_list.addItem(QListWidgetItem(tag))
            for i in range(self.tags_list.count()):
                item = self.tags_list.item(i)
                item.setSelected(item.text() in self.card.tags)
        
        form = QVBoxLayout(spacing=15)
        form.addWidget(QLabel("标题:"))
        form.addWidget(self.title_input)
        form.addWidget(QLabel("答案:"))
        form.addWidget(self.answer_input)
        form.addWidget(QLabel("标签:"))
        form.addWidget(self.tags_list)
        
        buttons = QHBoxLayout()
        ok_btn = QPushButton("保存" if self.card else "创建")
        ok_btn.setStyleSheet("""
            QPushButton {
                background: #3498db;
                color: white;
                padding: 12px 25px;
                border-radius: 6px;
                font: bold 14px Segoe UI;
            }
            QPushButton:hover { background: #2980b9; }
        """)
        ok_btn.clicked.connect(self.accept)
        
        cancel_btn = QPushButton("取消")
        cancel_btn.setStyleSheet("""
            QPushButton {
                background: #95a5a6;
                color: white;
                padding: 12px 25px;
                border-radius: 6px;
                font: 14px Segoe UI;
            }
            QPushButton:hover { background: #7f8c8d; }
        """)
        cancel_btn.clicked.connect(self.reject)
        
        buttons.addStretch()
        buttons.addWidget(cancel_btn)
        buttons.addWidget(ok_btn)
        
        layout.addLayout(form)
        layout.addLayout(buttons)
        self.setLayout(layout)
    
    def get_card_data(self):
        selected_tags = [item.text() for item in self.tags_list.selectedItems()]
        return {
            'title': self.title_input.text().strip(),
            'answer': self.answer_input.toPlainText().strip(),
            'tags': selected_tags  # 返回标签列表
        }

class StudyDialog(QDialog):
    def __init__(self, cards, parent=None):
        super().__init__(parent)
        self.cards = cards
        self.current_index = 0
        self.initUI()
        self.setupShortcuts()
        self.show_card() 
        
    def initUI(self):
        self.setWindowTitle("学习模式")
        self.setMinimumSize(800, 600)
        self.setStyleSheet("background: #f8f9fa;")
        
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(30, 30, 30, 30)
        
        self.card_frame = QFrame()
        self.card_frame.setStyleSheet("""
            background: white;
            border-radius: 15px;
            padding: 30px;
        """)
        frame_layout = QVBoxLayout()
        
        self.title_label = QLabel()
        self.title_label.setAlignment(Qt.AlignCenter)
        self.title_label.setFont(QFont("Segoe UI", 19, QFont.Bold))
        self.title_label.setStyleSheet("color: #2c3e50; margin-bottom: 20px;")
        self.title_label.setWordWrap(True) 

        self.answer_label = QLabel()
        self.answer_label.setAlignment(Qt.AlignCenter)
        self.answer_label.setFont(QFont("Segoe UI", 15))
        self.answer_label.setStyleSheet("color: #7f8c8d; padding: 20px;")
        self.answer_label.hide()
        self.answer_label.setWordWrap(True) 

        frame_layout.addWidget(self.title_label)
        frame_layout.addWidget(self.answer_label)
        self.card_frame.setLayout(frame_layout)
        
        btn_layout = QHBoxLayout()
        btn_layout.setSpacing(15)
        
        buttons = [
            ("陌生 (1)", "#e74c3c"),
            ("不熟 (2)", "#f1c40f"), 
            ("掌握 (3)", "#2ecc71")
        ]
        
        for text, color in buttons:
            btn = QPushButton(text)
            btn.setFixedHeight(45)
            btn.setFont(QFont("Segoe UI", 12, QFont.Bold))
            darker = self.darker_color(color)
            btn.setStyleSheet(f"""
                QPushButton {{
                    background: {color};
                    color: white;
                    border-radius: 8px;
                }}
                QPushButton:hover {{ background: {darker}; }}
            """)
            btn.clicked.connect(lambda _, i=buttons.index((text, color))+1: self.handle_answer(i))
            btn_layout.addWidget(btn)
        
        main_layout.addWidget(self.card_frame)
        main_layout.addLayout(btn_layout)
        self.setLayout(main_layout)
        self.setupShadow()
        
    def darker_color(self, hex_color, factor=0.8):
        color = QColor(hex_color)
        if not color.isValid():
            return "#000000"
        return color.darker(int(factor * 100)).name()
        
    def setupShadow(self):
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(20)
        shadow.setColor(QColor(0,0,0,30))
        shadow.setOffset(5,5)
        self.card_frame.setGraphicsEffect(shadow)
        
    def setupShortcuts(self):
        QShortcut(QKeySequence("1"), self).activated.connect(lambda: self.handle_answer(1))
        QShortcut(QKeySequence("2"), self).activated.connect(lambda: self.handle_answer(2))
        QShortcut(QKeySequence("3"), self).activated.connect(lambda: self.handle_answer(3))
        QShortcut(Qt.Key_Space, self).activated.connect(self.toggle_answer)
        QShortcut(Qt.Key_Q, self).activated.connect(self.prev_card)
        QShortcut(Qt.Key_E, self).activated.connect(self.next_card)
        
    def toggle_answer(self):
        self.answer_label.setVisible(not self.answer_label.isVisible())
        if self.answer_label.isVisible():
            self.title_label.setAlignment(Qt.AlignTop)
            self.title_label.setStyleSheet("color: #2c3e50; margin-bottom: 10px;")
        else:
            self.title_label.setAlignment(Qt.AlignCenter)
            self.title_label.setStyleSheet("color: #2c3e50; margin-bottom: 20px;")
            
    def show_card(self):
        card = self.cards[self.current_index]
        self.title_label.setText(card.title)
        self.answer_label.setText(card.answer)
        self.answer_label.hide()
        
    def prev_card(self):
        self.current_index = max(0, self.current_index - 1)
        self.show_card()
        
    def next_card(self):
        self.current_index = min(len(self.cards)-1, self.current_index + 1)
        self.show_card()
        
    def handle_answer(self, level):
        card = self.cards[self.current_index]
        if level == 1:
            card.update_proficiency(-20)
        elif level == 3:
            card.update_proficiency(20)
        
        if self.current_index == len(self.cards) - 1:
            self.accept()
        else:
            self.next_card()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.cards = []
        self.tags = []
        self.initUI()
        self.load_data()
        
    def initUI(self):
        self.setWindowTitle("记忆卡片")
        self.setGeometry(100, 100, 1200, 800)
        self.setStyleSheet("""
            background: #f8f9fa;
            font-family: Segoe UI;
        """)
        
        self.setupMenu()
        self.setupShortcuts()
        self.setupMainUI()
        
    def setupMenu(self):
        menubar = self.menuBar()
        
        file_menu = menubar.addMenu("文件")
        file_actions = [
            ("新建文件夹 (N)", "Ctrl+N", self.create_folder),
            ("新建卡片 (A)", "Ctrl+A", self.create_card),
            ("学习模式 (S)", "Ctrl+S", self.start_study),
            ("保存数据", "Ctrl+W", self.save_data),
            ("退出", "Ctrl+Q", self.close)
        ]
        for text, shortcut, handler in file_actions:
            action = QAction(text, self)
            action.setShortcut(QKeySequence(shortcut))
            action.triggered.connect(handler)
            file_menu.addAction(action)
            
        tool_menu = menubar.addMenu("工具")
        tool_actions = [
            ("导入卡片", self.import_cards),
            ("导出当前标签", self.export_current_tag)
        ]
        for text, handler in tool_actions:
            action = QAction(text, self)
            action.triggered.connect(handler)
            tool_menu.addAction(action)
            
    def setupShortcuts(self):
        QShortcut(QKeySequence("h"), self).activated.connect(self.show_help)
        QShortcut(QKeySequence("o"), self).activated.connect(self.show_settings)
        
    def setupMainUI(self):
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        layout = QHBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)
        
        self.tag_list = QListWidget()
        self.tag_list.setFixedWidth(280)
        self.tag_list.setFont(QFont("Segoe UI", 12))
        self.tag_list.setStyleSheet("""
            QListWidget {
                background: white;
                border-radius: 10px;
                padding: 10px;
                border: 1px solid rgba(0,0,0,0.05);
            }
            QListWidget::item {
                padding: 15px;
                border-radius: 8px;
                margin: 5px 0;
            }
            QListWidget::item:selected {
                background: #3498db;
                color: white;
            }
        """)
        self.tag_list.itemClicked.connect(self.show_tag_cards)
        self.tag_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tag_list.customContextMenuRequested.connect(self.show_tag_context_menu)
        layout.addWidget(self.tag_list)
        
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setStyleSheet("border: none; background: transparent;")
        
        self.card_container = QWidget()
        self.card_layout = QGridLayout()
        self.card_layout.setAlignment(Qt.AlignTop)
        self.card_layout.setHorizontalSpacing(20)
        self.card_layout.setVerticalSpacing(25)
        self.card_container.setLayout(self.card_layout)
        
        scroll.setWidget(self.card_container)
        layout.addWidget(scroll)
        
        main_widget.setLayout(layout)
        
    def show_tag_context_menu(self, pos):
        item = self.tag_list.itemAt(pos)
        if not item:
            return
            
        menu = QMenu()
        delete_action = QAction("删除文件夹", self)
        delete_action.triggered.connect(lambda: self.delete_folder(item))
        menu.addAction(delete_action)
        menu.exec_(self.tag_list.viewport().mapToGlobal(pos))
        
    def delete_folder(self, item):
        tag_name = item.text()
        # 移除所有卡片中的该标签
        for card in self.cards:
            if tag_name in card.tags:
                card.tags.remove(tag_name)
        # 更新数据
        self.tags.remove(tag_name)
        self.update_tag_list()
        self.show_tag_cards()
        self.save_data()
        
    def resizeEvent(self, event):
        self.adjustCardLayout()
        super().resizeEvent(event)
        
    def adjustCardLayout(self):
        container_width = self.card_container.width() - 40
        min_card_width = CardWidget.MIN_WIDTH
        max_card_width = CardWidget.MAX_WIDTH
        
        available_width = container_width - self.card_layout.horizontalSpacing() * 2
        columns = max(1, available_width // (min_card_width + self.card_layout.horizontalSpacing()))
        column_width = min(
            max_card_width, 
            (available_width - self.card_layout.horizontalSpacing() * (columns - 1)) // columns
        )
        
        for i in range(self.card_layout.count()):
            item = self.card_layout.itemAt(i)
            if widget := item.widget():
                widget.setFixedWidth(column_width)
                widget.setFixedHeight(int(column_width * CardWidget.ASPECT_RATIO))
        
    def show_help(self):
        help_text = """快捷键指南：
        Ctrl+N - 新建文件夹
        Ctrl+A - 新建卡片
        Ctrl+S - 开始学习
        Ctrl+W - 保存数据
        Ctrl+Q - 退出程序
        H - 显示帮助
        O - 打开设置
        
        学习模式快捷键：
        Q - 上一个卡片
        E - 下一个卡片
        空格 - 显示答案
        1/2/3 - 选择熟练度"""
        QMessageBox.information(self, "帮助", help_text)
        
    def show_settings(self):
        QMessageBox.information(self, "设置", "设置功能开发中，敬请期待...")
        
    def create_folder(self):
        tag, ok = QInputDialog.getText(self, "新建文件夹", "输入新标签名称:")
        if ok and tag:
            if tag not in self.tags:
                self.tags.append(tag)
                self.update_tag_list()
                self.save_data()
                
    def update_tag_list(self):
        self.tag_list.clear()
        for tag in self.tags:
            item = QListWidgetItem(tag)
            item.setFont(QFont("Segoe UI", 12))
            self.tag_list.addItem(item)
            
    def create_card(self):
        if not self.tags:
            QMessageBox.warning(self, "错误", "请先创建至少一个标签文件夹")
            return
            
        dialog = NewCardDialog(self.tags, parent=self)
        if dialog.exec_():
            new_data = dialog.get_card_data()
            if not new_data['title'] or not new_data['answer']:
                QMessageBox.warning(self, "输入错误", "标题和答案不能为空")
                return
                
            new_card = Card(
                new_data['title'],
                new_data['answer'],
                new_data['tags']
            )
            self.cards.append(new_card)
            self.show_tag_cards()
            self.save_data()
            
    def show_tag_cards(self):
        while self.card_layout.count():
            item = self.card_layout.takeAt(0)
            if widget := item.widget():
                widget.deleteLater()
                
        if not self.tag_list.selectedItems():
            return
            
        current_tag = self.tag_list.currentItem().text()
        filtered = [c for c in self.cards if current_tag in c.tags]  # 使用in判断
        row = col = 0
        max_columns = self.calculate_max_columns()
        
        for card in filtered:
            card_widget = CardWidget(card)
            card_widget.doubleClicked.connect(lambda c=card: self.preview_card(c))
            card_widget.rightClicked.connect(lambda c=card: self.show_context_menu(c))
            self.card_layout.addWidget(card_widget, row, col)
            
            col += 1
            if col >= max_columns:
                col = 0
                row += 1
        
        self.adjustCardLayout()
                
    def calculate_max_columns(self):
        container_width = self.card_container.width() - 40
        min_card_width = CardWidget.MIN_WIDTH
        return max(1, container_width // (min_card_width + self.card_layout.horizontalSpacing()))
    
    def show_context_menu(self, card):
        menu = QMenu(self)
        
        edit_action = QAction("编辑卡片", self)
        edit_action.triggered.connect(lambda: self.edit_card(card))
        
        delete_action = QAction("删除卡片", self)
        delete_action.triggered.connect(lambda: self.delete_card(card))
        
        menu.addAction(edit_action)
        menu.addAction(delete_action)
        menu.exec_(QCursor.pos())
        
    def preview_card(self, card):
        dialog = PreviewDialog(card, self)
        dialog.exec_()
        
    def edit_card(self, card):
        dialog = NewCardDialog(self.tags, card, self)
        if dialog.exec_():
            new_data = dialog.get_card_data()
            # 更新卡片数据
            card.title = new_data['title']
            card.answer = new_data['answer']
            card.tags = [t.strip() for t in new_data['tags'] if t.strip()]
            
            # 更新全局标签列表
            for tag in card.tags:
                if tag not in self.tags:
                    self.tags.append(tag)
                    self.update_tag_list()
            
            # 强制刷新
            self.show_tag_cards()
            self.save_data()
        
    def delete_card(self, card):
        confirm = QMessageBox.question(
            self, 
            "确认删除",
            f"确定要永久删除卡片【{card.title}】吗？",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if confirm == QMessageBox.Yes:
            self.cards.remove(card)
            self.show_tag_cards()
            self.save_data()
        
    def start_study(self):
        # 弹出标签选择对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("选择学习标签")
        layout = QVBoxLayout()
        tags_list = QListWidget()
        tags_list.setSelectionMode(QListWidget.MultiSelection)
        for tag in self.tags:
            tags_list.addItem(QListWidgetItem(tag))
        layout.addWidget(tags_list)

        btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(dialog.accept)
        btn_box.rejected.connect(dialog.reject)
        layout.addWidget(btn_box)
        dialog.setLayout(layout)

        if dialog.exec_() != QDialog.Accepted:
            return

        selected_tags = [item.text() for item in tags_list.selectedItems()]
        if not selected_tags:
            QMessageBox.warning(self, "错误", "请选择至少一个标签")
            return

        # 初步筛选：包含任一选中标签的卡片
        filtered = [c for c in self.cards if any(tag in c.tags for tag in selected_tags)]
        if not filtered:
            QMessageBox.information(self, "提示", "所选标签下没有卡片")
            return

        # 二次筛选：需要复习的卡片
        filtered = [
            c for c in filtered 
            if (c.proficiency < 100 or 
                (c.proficiency >= 100 and 
                 (datetime.now() - c.last_practiced) > timedelta(days=3)))
        ]
        if not filtered:
            QMessageBox.information(self, "提示", "当前没有需要复习的卡片")
            return

        # 按熟练度排序
        filtered.sort(key=lambda x: x.proficiency)

        # 应用遗忘衰减
        for card in filtered:
            card.decay_proficiency()

        # 启动学习对话框
        study_dialog = StudyDialog(filtered, self)
        study_dialog.exec_()

        # 更新界面并保存
        self.show_tag_cards()
        self.save_data()

    def import_cards(self):
        if not self.tags:
            QMessageBox.warning(self, "错误", "请先创建至少一个标签")
            return
            
        path, _ = QFileDialog.getOpenFileName(
            self, "选择导入文件", "", "JSON文件 (*.json)")
        if not path:
            return
            
        try:
            with open(path, 'r', encoding='utf-8') as f:
                data = load(f)
                current_tag = self.tag_list.currentItem().text() if self.tag_list.currentItem() else None
                
                count = 0
                for item in data:
                    tags = item.get('tags', [])
                    if 'tag' in item:  # 兼容旧数据
                        tags.append(item['tag'])
                    # 添加新标签到全局列表
                    for tag in tags:
                        if tag not in self.tags:
                            self.tags.append(tag)
                    # 创建卡片...
                    self.cards.append(Card.from_dict(item))
                self.update_tag_list()
                            
                self.show_tag_cards()
                self.save_data()
                QMessageBox.information(self, "导入完成", f"成功导入{count}张卡片")
                
        except Exception as e:
            QMessageBox.critical(self, "导入失败", f"文件格式错误：{str(e)}")

    def export_current_tag(self):
        if not self.tag_list.currentItem():
            QMessageBox.warning(self, "错误", "请先选择要导出的标签")
            return
            
        current_tag = self.tag_list.currentItem().text()
        
        path, _ = QFileDialog.getSaveFileName(
            self, "选择保存位置", f"{current_tag}_cards.json", "JSON文件 (*.json)")
        if not path:
            return
            
        try:
            export_data = [c.to_dict() for c in self.cards if current_tag in c.tags]
            with open(path, 'w', encoding='utf-8') as f:
                dump(export_data, f, ensure_ascii=False, indent=2)
                
            QMessageBox.information(self, "导出成功", f"已导出{len(export_data)}张卡片")
        except Exception as e:
            QMessageBox.critical(self, "导出失败", f"保存文件时出错：{str(e)}")
        
    def save_data(self):
        data = {
            'tags': self.tags,
            'cards': [c.to_dict() for c in self.cards]
        }
        try:
            with open(SAVE_FILE, 'w', encoding='utf-8') as f:
                dump(data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            QMessageBox.critical(self, "保存失败", f"数据保存失败：{str(e)}")
            
    def load_data(self):
        try:
            with open(SAVE_FILE, 'r', encoding='utf-8') as f:
                data = load(f)
                self.tags = data['tags']
                self.cards = [Card.from_dict(c) for c in data['cards']]
                self.update_tag_list()
        except FileNotFoundError:
            pass
        except Exception as e:
            QMessageBox.warning(self, "加载错误", f"数据加载失败：{str(e)}")
            
    def closeEvent(self, event):
        self.save_data()
        event.accept()

if __name__ == "__main__":
    app = QApplication(argv)
    app.setStyle("Fusion")
    
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(248, 249, 250))
    palette.setColor(QPalette.Base, QColor(255, 255, 255))
    palette.setColor(QPalette.Button, QColor(240, 240, 240))
    app.setPalette(palette)
    
    font = QFont("Segoe UI", 12)
    app.setFont(font)
    
    window = MainWindow()
    window.show()
    exit(app.exec_())